//
//  CaseViewController.m
//  HomeFurnishing
//
//  Created by dllo on 16/3/25.
//  Copyright © 2016年 YMing. All rights reserved.
//

#import "CaseViewController.h"
#import "CaseTableViewCell.h"
#import "ActivitySrcollView.h"
#import "doubleTableView.h"
#import "SetupViewController.h"
#import "CaseBaseModel.h"
#import "DetailCaseVC.h"
#import "DetailDCaseVC.h"
#import "SiftViewController.h"

@interface CaseViewController ()<UITableViewDelegate, UITableViewDataSource, DTableViewDelegate,ActivitySVDelegate>
@property(nonatomic, retain) UITableView *tableView;
@property(nonatomic, retain) UIScrollView *scrView;/**< 底部滚动视图*/
@property(nonatomic, retain) UITableView *rightTableView;/**< 在线施工TableView*/
@property(nonatomic, assign) BOOL isChange;
@property(nonatomic, retain) NSMutableArray *dataArr;
@property(nonatomic, retain) NSMutableArray *imgArr;/**< 轮播图图片数组*/
@property(nonatomic, retain) CATransition *transition;
@property(nonatomic, assign) NSInteger num;
@property(nonatomic, retain)UIColor *lineColor;
@property (nonatomic, assign)CGFloat lineHeight;
@property(nonatomic,retain)UIView *lineView;
@property (nonatomic, assign, getter=isHidden) BOOL lineIsHidden;
@property(nonatomic, retain)MBProgressHUD *HUD;
@end

@implementation CaseViewController

-(void)dealloc
{
    [_tableView release];
    [_scrView release];
    [_rightTableView release];
    [_dataArr release];
    [_transition release];
    [_HUD release];
    [super dealloc];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [[DataBaseManager shareInstance] openDB];
    [[DataBaseManager shareInstance] createTable];
    [[DataBaseManager shareInstance] createTableS];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    self.navigationItem.title = @"装修案例";
    self.transition = [CATransition animation];
    self.navigationController.navigationBar.barTintColor = [UIColor cyanColor];
    self.navigationController.navigationBar.tintColor = [UIColor grayColor];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"设置"style:(UIBarButtonItemStyleDone) target:self action:@selector(choice)];
    
    
    [self createScrollView];
    [self createTableView];
    [self createRightTableView];
    //[self dataHandle];
    [self addBtn];
    [self tableViewAddHeaderAndFooter];
}
//设置菊花
- (void)tableViewAddHeaderAndFooter
{
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        self.isChange = NO;
        self.num = 0;
        [self dataHandle];
        
    }];
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        self.isChange = YES;
        self.num++;
        [self dataHandle];
    }];
    [self.tableView.header beginRefreshing];
}
-(void)loadNewData
{
    
}
/**
 *  数据获取
 */
-(void)dataHandle
{
    NSInteger count = (self.num +1)*10;
    NSString *str = [NSString stringWithFormat:@"http://api.guju.com.cn/v2/project?start=0&count=%ld&user=(null)&style=0&type=0&area=0&cost=0",count];
    [NetworkHandle GetDataWithURL:str dic:nil success:^(id responseObject) {
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
        if (self.isChange) {
            [self.dataArr removeAllObjects];
        }
        self.dataArr = [CaseBaseModel transformWithArray:responseObject[@"projects"]];
        [_tableView reloadData];
    } filed:^(NSError *error) {
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
    }];
}

/**
 *  创建底部滚动视图
 */
-(void)createScrollView
{
    self.scrView = [[UIScrollView alloc] initWithFrame:SCREEN_FRAME];
    _scrView.contentSize = CGSizeMake(SCREEN_WIDTH * 2, 0);
//    _scrView.contentInset =UIEdgeInsetsMake(64, 0, 0, 0);
    _scrView.pagingEnabled = YES;
    _scrView.alwaysBounceHorizontal = YES;
    _scrView.bounces = NO;
    _scrView.backgroundColor = [UIColor whiteColor];
    _scrView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_scrView];
    [_scrView release];
}
/**
 *  轮播图点击协议方法
 
 * *  @param page 点击图片在数组的下标
 */
-(void)didSelectImageAtPage:(NSInteger)page
{
    DetailCaseVC *VC = [[DetailCaseVC alloc] init];
    VC.model = [[CaseBaseModel alloc] init];
    NSString *str = [NSString stringWithFormat:@"http://api.guju.com.cn/v2/project/%@",_imgArr[page]];
    //NSString *strUrl = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
   // NSLog(@"%@",str);
    [NetworkHandle GetDataWithURL:str dic:nil success:^(id responseObject) {
        [VC.model setValuesForKeysWithDictionary:responseObject];
        VC.hidesBottomBarWhenPushed = YES;
        //NSLog(@"%@",responseObject);
        self.navigationController.navigationBarHidden = YES;
        [self.navigationController pushViewController:VC animated:YES];
        [VC release];
        [VC.model release];
    } filed:^(NSError *error) {
        
    }];
}

/**
 *  创建TableView
 */
-(void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 94, SCREEN_WIDTH, SCREEN_HEIGHT - 49-64-30) style:(UITableViewStylePlain)];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.tableView.tableFooterView =[[UIView alloc] init];
        _tableView.rowHeight = 270;
        //设置tableview的contentView距离上边界30
        //相对于0点,已经向下偏移了-30
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        [_tableView release];
    
        [_scrView addSubview:_tableView];
        [_tableView registerClass:[CaseTableViewCell class] forCellReuseIdentifier:@"CaseTableViewCell"];
        [self createView];
}

/**
 *  创建右侧tableView
 *
 *  @return doubleView
 */
-(void)createRightTableView
{
    doubleTableView *rightTV = [[doubleTableView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH, 30+64, SCREEN_WIDTH, SCREEN_HEIGHT-30-64-49)];
    [_scrView addSubview:rightTV];
    rightTV.delegate = self;
    [rightTV release];
}
/**
 *  添加按钮
 */
-(void)addBtn
{
    UIButton *leftBtn = [UIButton buttonWithType:(UIButtonTypeSystem)];
    leftBtn.frame = CGRectMake(0, 0, SCREEN_WIDTH/2, 30*kHeight);
    [leftBtn setTitle:@"精选推荐" forState:(UIControlStateNormal)];
    [leftBtn setTintColor:[UIColor brownColor]];
    [leftBtn addTarget:self action:@selector(leftButt:) forControlEvents:(UIControlEventTouchUpInside)];
    UIButton *rightBtn = [UIButton buttonWithType:(UIButtonTypeSystem)];
    rightBtn.frame = CGRectMake(SCREEN_WIDTH/2, 0, SCREEN_WIDTH/2, 30);
    [rightBtn setTitle:@"在线施工" forState:(UIControlStateNormal)];
    [rightBtn setTintColor:[UIColor brownColor]];
    [rightBtn addTarget:self action:@selector(rightButt:) forControlEvents:(UIControlEventTouchUpInside)];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, 30)];
    view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view];
    [view addSubview:leftBtn];
    [view addSubview:rightBtn];

    [view release];
    UIView *lineView = [[UIView alloc] init];
    self.lineView = lineView;
    self.lineView.backgroundColor = self.lineColor;
    self.lineView.frame = CGRectMake(self.scrView.contentOffset.x/2, 30-self.lineHeight, SCREEN_WIDTH/2, self.lineHeight);
    [view addSubview:self.lineView];
}
-(UIColor *)lineColor
{
    if (_lineColor == nil) {
        _lineColor = [UIColor orangeColor];
    }
    return _lineColor;
}
/**
 *  下划线高度
 */
-(CGFloat)lineHeight
{
    if (_lineHeight == 0) {
        _lineHeight = 2;
    }
    return _lineHeight;
}
/**
 *  添加轮播图
 */
-(void)createView
{
    ActivitySrcollView *sv = [[ActivitySrcollView alloc] initWithFrame:CGRectMake(0, 94, SCREEN_WIDTH, 210*kHeight)];
    //sv.backgroundColor = [UIColor redColor];
       self.tableView.tableHeaderView = sv;
    sv.delegate = self;
    /**
     *  轮播图数据获取
     */
    NSMutableArray *arr = [NSMutableArray array];
    self.imgArr = [NSMutableArray array];
    [NetworkHandle GetDataWithURL:@"http://api.guju.com.cn/v2/project/banner?src=appBannerOfProject" dic:nil success:^(id responseObject) {
        //NSLog(@"%@",responseObject);
        for (NSDictionary *dic in responseObject[@"banners"]) {
            [arr addObject:dic[@"imgUrl"]];
            [_imgArr addObject:dic[@"httpUrl"]];
        }
        [sv setImages:arr];
    } filed:^(NSError *error) {
        
    }];
    [sv release];

}
/**
 *  导航栏右侧按钮
 */
-(void)choice
{
    SetupViewController *Svc = [[SetupViewController alloc] init];
    Svc.hidesBottomBarWhenPushed = YES;
    _transition.duration = 2;
    _transition.repeatCount = 1;
    //滴水效果
    _transition.type = @"rippleEffect";
    //动画方向
    _transition.subtype = kCATransitionFromBottom;
    [self.navigationController.view.layer addAnimation:_transition forKey:@"啦啦啦"];
    [self.navigationController pushViewController:Svc animated:NO];
}
/**
 *  左侧按钮(精选推荐)
 */
-(void)leftButt:(UIButton *)btn
{
    _scrView.contentOffset = CGPointZero;
    self.lineView.frame = CGRectMake(self.scrView.contentOffset.x/2, 30-self.lineHeight, SCREEN_WIDTH/2, self.lineHeight);
}
/**
 *  右侧按钮(在线施工)
 */

-(void)rightButt:(UIButton *)btn
{
    _scrView.contentOffset = CGPointMake(SCREEN_WIDTH, 0);
    self.lineView.frame = CGRectMake(self.scrView.contentOffset.x/2, 30-self.lineHeight, SCREEN_WIDTH/2, self.lineHeight);
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    CaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CaseTableViewCell" forIndexPath:indexPath];
    //cell.backgroundColor = [UIColor cyanColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    CaseBaseModel *m = _dataArr[indexPath.row];
    cell.title.text = m.title;
    cell.styleShow.text = m.styleShow;
    cell.typeShow.text = m.typeShow;
    cell.areaShow.text = [NSString stringWithFormat:@"%@平米",m.areaShow];
    cell.costShow.text = [NSString stringWithFormat:@"%@万元",m.cost];
    NSString *str = [NSString stringWithFormat:@"http://gooju.cn/dimages/%@_0_w750_h398_m0.jpg",m.coverPhoto];
    [cell.imgView sd_setImageWithURL:[NSURL URLWithString:str] placeholderImage:[UIImage imageNamed:@"24099F061BD92F37796E9B75C3ED9531.jpg"]];
    cell.mId = m.coverPhoto;
    [cell.userImgView sd_setImageWithURL:[NSURL URLWithString:m.large]];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailCaseVC *VC = [[DetailCaseVC alloc] init];
    VC.model = _dataArr[indexPath.row];
    VC.hidesBottomBarWhenPushed = YES;
    _transition.duration = 2;
    _transition.repeatCount = 1;
    //动画的类型
    _transition.type = @"suckEffect";
    //动画方向
    //_transition.subtype = kCATransitionFromLeft;
    [self.navigationController.view.layer addAnimation:_transition forKey:@"啦啦啦"];
    [self.navigationController pushViewController:VC animated:NO];
    [VC release];
}
/**
 *  右侧TableView协议方法
 *
 *  @param indexPath 下标
 *  @param arr       数据
 */
-(void)didSelectRowAtIndexPath:(NSIndexPath *)indexPath array:(NSArray *)arr
{
    DetailDCaseVC *VC = [[DetailDCaseVC alloc] init];
    VC.hidesBottomBarWhenPushed = YES;
    CaseDBaseModel *m = arr[indexPath.row];
    VC.mId = m.mId;
    VC.index = indexPath;
    VC.model = m;
//    NSLog(@"%@",VC.mId);
//    NSLog(@"%@",VC.model.title);
    _transition.duration = 2;
    _transition.repeatCount = 1;
    //动画的类型
    _transition.type = kCATransitionFade;
    //动画方向
    _transition.subtype = kCATransitionFromLeft;
    [self.navigationController.view.layer addAnimation:_transition forKey:@"啦啦啦"];
    [self.navigationController pushViewController:VC animated:NO];
    [VC release];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

/**
 *  在view里获取viewController对象
 *
 *  @param UIViewController 响应者链
 *
 *  @return 返回所需响应的VC
 */

//- (UIViewController *)viewController {
//    for (UIView* next = [self superview]; next; next = next.superview) {
//        UIResponder *nextResponder = [next nextResponder];
//        if ([nextResponder isKindOfClass:[UIViewController class]]) {
//            return (UIViewController *)nextResponder;
//        }
//    }
//    return nil;
//}
@end
